import type { RedisClient } from "@linksaas-minapp/redis-proxy-api"
import { Button, Input } from "antd"
import { useState, useEffect } from "react"

export interface StringValueProps {
    client: RedisClient;
    curKey: string;
}

function StringValue(props: StringValueProps) {
    const [strValue, setStrValue] = useState("");
    const [hasChange, setHasChange] = useState(false);

    const loadData = async () => {
        const value = await props.client.strCommand().get(props.curKey);
        setStrValue(value ?? "");
    }

    const updateData = async () => {
        await props.client.strCommand().set(props.curKey, strValue, "", false, "KEEPTTL");
        setHasChange(false);
    };

    useEffect(() => {
        loadData();
    }, []);

    return (
        <div style={{ display: "flex" }}>
            <Input style={{ flex: 1 }} value={strValue} onChange={e => {
                e.stopPropagation();
                e.preventDefault();
                setStrValue(e.target.value);
                setHasChange(true);
            }} />
            <Button disabled={!hasChange} style={{ marginLeft: "10px", marginRight: "10px" }} onClick={e => {
                e.stopPropagation();
                e.preventDefault();
                loadData();
                setHasChange(false);
            }}>取消</Button>
            <Button disabled={!hasChange} type="primary" onClick={e => {
                e.stopPropagation();
                e.preventDefault();
                updateData();
            }}>更新</Button>
        </div>
    );
}

export default StringValue;
